package com.sj.uabrowser.mvp.main.view.act;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.daimajia.numberprogressbar.NumberProgressBar;
import com.orhanobut.logger.Logger;
import com.sj.uabrowser.BuildConfig;
import com.sj.uabrowser.MainActivity;
import com.sj.uabrowser.R;
import com.sj.uabrowser.app.StatusBarUtil;
import com.sj.uabrowser.app.Util;
import com.sj.uabrowser.db.Search;
import com.sj.uabrowser.db.gen.FileInfoDao;
import com.sj.uabrowser.db.gen.SearchDao;
import com.sj.uabrowser.framework.BaseActivity;
import com.sj.uabrowser.framework.BasePresenter;
import com.sj.uabrowser.mvp.main.view.adp.SearchContentAdp;
import com.sj.uabrowser.db.FileInfo;
import com.sj.uabrowser.mvp.menu.service.DownloadService;
import com.sj.uabrowser.mvp.menu.view.act.DownloadAct;
import com.sj.uabrowser.mvp.menu.view.act.EditFileNameAct;
import com.umeng.analytics.MobclickAgent;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

public class SearchAct extends BaseActivity implements TextWatcher, AdapterView.OnItemClickListener {

    public static final int RESULTCODE_KEYWORDS = 1;
    public static final int RESULTCODE_WEBSITE = 2;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.et_search)
    EditText etContent;
    @BindView(R.id.lvSearch)
    ListView lvSearch;
    @BindView(R.id.progressBar)
    NumberProgressBar progressBar;
    @BindView(R.id.rl_clear)
    View rlClear;

    private String baseUrl;
    private String DEMO_URL;


    private List<Search> searches = new ArrayList<>();
    private List<Search> searches0 = new ArrayList<>();

    private SearchContentAdp adp;

    String contentLength = "0";
    Thread wThread = null;
    Timer timer = null;
    int progress = 0;

    private SearchDao searchDao;
    private View popDownload;
    private PopupWindow popupWindowDownload;
    private FileInfo fileInfo;

    @OnClick(R.id.tv_clear_list)
    public void onClearList(View view){
        startIconAnim(view);
        searchDao.deleteAll();
        searches.clear();
        adp.notifyDataSetChanged();
        rlClear.setVisibility(View.GONE);
    }

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_search;
    }
    @Override
    public void setView() {
//        statusbar.setBackgroundResource(R.drawable.shape_gradient);
        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);
        StatusBarUtil.setLightMode(this);
        searchDao = daoSession.getSearchDao();
        baseUrl = getIntent().getStringExtra("searchUrl");
        etContent.addTextChangedListener(this);
        etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }
                    if(BuildConfig.UM) {
                        String eventid= "search-search";
                        MobclickAgent.onEvent(SearchAct.this, eventid,"搜索-搜索_框");
                    }
                    doClickSearch();
                    return true;
                }
                return false;
            }
        });



    }

    @Override
    public void setData() {
        if (searchDao != null)
            searches0 = searchDao.queryRaw("order by date desc");
        if (searches0 != null && searches0.size() > 0) {
            searches.addAll(searches0);
        }
        adp = new SearchContentAdp(searches);
        lvSearch.setAdapter(adp);
        lvSearch.setOnItemClickListener(this);
        String httpurl = getIntent().getStringExtra("httpurl");
        if (!TextUtils.isEmpty(httpurl)) {
            etContent.setText(httpurl);
            doClickSearch();
        }

        String url = getIntent().getStringExtra("url");
        if(!TextUtils.isEmpty(url)&&isUrl(url)){
            etContent.setText(url);
        }
    }

    @OnClick({R.id.tv_cancel, R.id.iv_clear/*, R.id.tv_clear*/})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                finish();
                break;

            case R.id.iv_clear:
                etContent.setText("");
                break;
//            case R.id.tv_clear:
//                if(session!=null)
//                session.getSearchDao().deleteAll();
//                searches.clear();
//                adp.notifyDataSetChanged();
//                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (TextUtils.isEmpty(s)) {
            if (searchDao != null)
                searches0 = searchDao.loadAll();
            if (searches0 != null && searches0.size() > 0) {
                searches.clear();
                searches.addAll(searches0);
            }
            ivClear.setVisibility(View.GONE);
        } else {
            searches0.clear();
            searches0.addAll(searches);
            searches.clear();
            ivClear.setVisibility(View.VISIBLE);
        }
        if(searches.size()==0){
            rlClear.setVisibility(View.GONE);
        }else{
            rlClear.setVisibility(View.VISIBLE);
        }
        adp.notifyDataSetChanged();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void doClickSearch() {
        String content = etContent.getText().toString().trim();
        Search search = new Search();
        search.setContent(content);
        if (isUrl(content)) {
            String url = content;
            if (!content.startsWith("http")) {
                url = "https://" + content;
            }
            search.setType(Search.CONTENT_URL);
            if (!contains(content)) {
                if (searchDao != null && !noTrace) searchDao.insert(search);
            }
            DEMO_URL = url;
            selectNetOrDownload();
        } else {
            search.setType(Search.CONTENT_KEYWORDS);
            goKeyWdAct(content);
            if (!contains(content)) {
                if (searchDao != null && !noTrace) searchDao.insert(search);
                hideKeyBoard(etContent);
            }
            finish();
        }
    }

    private void goKeyWdAct(String content) {
//        Intent intent = new Intent(this, KeyWdAct.class);
//        intent.putExtra("searchUrl", baseUrl + content);
//        intent.putExtra("keywords", content);
//        startActivity(intent);
        Intent intent = new Intent();
        intent.putExtra("keywords",content);
        setResult(RESULTCODE_KEYWORDS,intent);

    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            progress += 5;
            if (progress < 90) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (progressBar != null) progressBar.setProgress(progress);
                    }
                });
            } else {
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
            }
        }
    };

    private void selectNetOrDownload() {
//        etContent.setText(DEMO_URL);
        if (progressBar != null) progressBar.setVisibility(View.VISIBLE);
        if (timer != null) timer.scheduleAtFixedRate(task, 100, 200);
        wThread = new Thread() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                try {
                    Logger.e("demo_url:" + DEMO_URL);
                    URL url = new URL(DEMO_URL);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setRequestMethod("GET");
                    conn.connect();

                    Map<String, List<String>> map = conn.getHeaderFields();
                    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                        System.out.println("Key : " + entry.getKey() +
                                " ,Value : " + entry.getValue());
                        if (TextUtils.equals(entry.getKey(), "Content-Length")) {
                            List<String> content = entry.getValue();
                            if (content != null && content.size() > 0) {
                                contentLength = content.get(0);
                                break;
                            }
                        }
                    }
                    String headerField = conn.getHeaderField("content-Disposition");
                    final String contentType = conn.getHeaderField("Content-Type");
                    if (contentType == null || contentType.contains("text/html")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setProgress(100);
                                progressBar.setVisibility(View.GONE);
//                                startBrowserActivity(MODE_SONIC, DEMO_URL, "", BrowserActivity.WANGZHI);
                                goWebAct();
                            }
                        });
                    } else {
//                        contentLength = conn.getHeaderFieldInt("Content-Length",-1);
                        // 转换编码
                        if (headerField != null) {
                            String contentDisposition = URLDecoder.decode(headerField, "UTF-8");
                            System.out.println(contentDisposition);
                            // 匹配文件名
                            Pattern pattern = Pattern.compile(".*filename=(.*)");
                            Matcher matcher = pattern.matcher(contentDisposition);
                            System.out.println(matcher.groupCount());
                            System.out.println(matcher.matches());
                            System.out.println(matcher.group(1));
                            final String filename = matcher.group(1);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progressBar.setProgress(100);
                                    progressBar.setVisibility(View.GONE);

                                    if (!TextUtils.isEmpty(filename)) {

                                        String filename0 = filename.replaceAll("\"", "");

                                        if (filename0.contains(";")) {
                                            filename0 = filename0.split(";")[0];
                                        }
                                        final String downloadFileName = filename0;
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                showDownload(DEMO_URL, downloadFileName, Long.parseLong(contentLength));
                                            }
                                        });
                                    }
//                                    Intent intent = new Intent(SearchAct.this, DownloadAct.class);
//                                    intent.putExtra("file", DEMO_URL);
//                                    intent.putExtra("contentType", contentType);


//                                    intent.putExtra("contentLength", Long.parseLong(contentLength));
//                                    startActivity(intent);
//                                    finish();
                                }
                            });
                        } else {
                            progressBar.setProgress(100);
                            progressBar.setVisibility(View.GONE);
                            int startIndex = DEMO_URL.lastIndexOf("/");
                            int endIndex = DEMO_URL.length();
                            String filename = DEMO_URL.substring(startIndex + 1, endIndex);
                            if (!TextUtils.isEmpty(filename)) {
                                String filename0 = filename.replaceAll("\"", "");
                                if (filename0.contains(";")) {
                                    filename0 = filename0.split(";")[0];
                                }
                                final String downloadFileName = filename0;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showDownload(DEMO_URL, downloadFileName, Long.parseLong(contentLength));
                                    }
                                });
                            }
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    progressBar.setVisibility(View.GONE);
//                                    Intent intent = new Intent(SearchAct.this, DownloadAct.class);
//                                    intent.putExtra("file", DEMO_URL);
//                                    intent.putExtra("contentType", contentType);
//                                    if (!TextUtils.isEmpty(filename)) {
//                                        String filename0 = filename.replaceAll("\"", "");
//                                        intent.putExtra("filename", filename0);
//                                    }
//                                    intent.putExtra("contentLength", Long.parseLong(contentLength));
//                                    startActivity(intent);
//                                    finish();
//                                }
//                            });
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast("连接失败！");
                        }
                    });
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        };
        wThread.start();
    }

    private String editFileName;
    EditText etFileName;
    protected void showDownload(String url, String filename, long filesize) {
        editFileName = filename;
        popDownload = View.inflate(this, R.layout.popwindow_download_menu, null);
//        View popFull = popDownload.findViewById(R.id.ll_pop);
        View tvCancel = popDownload.findViewById(R.id.tv_download_cancel);
        View tvDownloadConfirm = popDownload.findViewById(R.id.tv_download_confirm);
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindowDownload != null) {
                    etFileName=null;
                    popupWindowDownload.dismiss();
                }
            }
        };
//        popFull.setOnClickListener(listener);
        tvCancel.setOnClickListener(listener);

        etFileName = popDownload.findViewById(R.id.et_download_filename);
        TextView tvFileSize = popDownload.findViewById(R.id.tv_download_filesize);
        ImageView ivEdit = popDownload.findViewById(R.id.iv_edit);
        ivEdit.setOnClickListener(v -> {
            Intent intentFN = new Intent(SearchAct.this, EditFileNameAct.class);
            intentFN.putExtra("filename",editFileName);
            startActivityForResult(intentFN,1);
        });
        etFileName.setText(editFileName);
        String filesizeStr = Util.getFileSize(filesize);
        tvFileSize.setText(String.format(getResources().getString(R.string.download_filesize), filesizeStr));
        tvDownloadConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etFileName.setEnabled(false);
                editFileName = etFileName.getText().toString().trim();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(grant -> {
                            if (grant) {
                                boolean res = startDownload(url.trim(), editFileName, filesize);
                                if (res) {
                                    if (popupWindowDownload != null) {
                                        etFileName=null;
                                        popupWindowDownload.dismiss();
                                    }
                                }
                            } else {
                                showToast("没有sd卡写入权限无法下载文件！");
                            }
                        });
                    }
                }, 500);
            }
        });
        popupWindowDownload = new PopupWindow(popDownload, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,true);
        popupWindowDownload.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindowDownload.setAnimationStyle(R.style.popwindow_anim);

        //让pop覆盖在输入法上面
        popupWindowDownload.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        //让pop自适应输入状态
        popupWindowDownload.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        if (Build.VERSION.SDK_INT >= 21) popupWindowDownload.setClippingEnabled(false);
        popupWindowDownload.setTouchable(true);
        popupWindowDownload.setOutsideTouchable(true);
        popupWindowDownload.showAtLocation(findViewById(R.id.container), Gravity.BOTTOM, 0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1){
            if(data!=null){
                String filename = data.getStringExtra("filename");
                if(etFileName!=null)etFileName.setText(filename);
            }
        }
    }

    private boolean startDownload(String url, String filename, long filesize) {
        fileInfo = new FileInfo(null, url, filename, filesize, 0L, true, new Date().getTime());
        FileInfoDao fileinfoDao = daoSession.getFileInfoDao();
        List<FileInfo> fileList = fileinfoDao.queryRaw("where url = ? and file_name = ?", new String[]{url, filename});
        if (fileList.size() == 0) {
            fileinfoDao.insert(fileInfo);
        } else {
            showToast("文件已存在，请修改文件名重新下载！");
            return false;
        }
        Intent downloadIntent = new Intent(SearchAct.this, DownloadService.class);
        downloadIntent.setAction(DownloadService.ACTION_START);
        downloadIntent.putExtra("fileInfo", fileInfo);
        startService(downloadIntent);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SearchAct.this, DownloadAct.class);
                startActivity(intent);
                finish();
            }
        }, 500);
        return true;
    }

    private void goWebAct() {
//        Intent intent = new Intent(SearchAct.this, BrowserAct.class);
//        intent.putExtra("type", BrowserAct.TYPE_SEARCH);
//        intent.putExtra("url", DEMO_URL);
//        startActivity(intent);
        Intent intent = new Intent();
        intent.putExtra("url",DEMO_URL);
        setResult(RESULTCODE_WEBSITE,intent);

        finish();
    }


    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (wThread != null) {
            wThread.interrupt();
            wThread = null;
        }
    }





    private boolean contains(String search) {
        if (searchDao != null)
            searches0 = searchDao.loadAll();
        boolean flag = false;
        for (int i = 0; i < searches0.size(); i++) {
            Search bean = searches0.get(i);
            if (TextUtils.equals(bean.getContent(), search)) {
                flag = true;
                bean.setDate(new Date().getTime());
                searchDao.update(bean);
                break;
            }
        }
        return flag;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(BuildConfig.UM) {
            String eventid= "search-search";
            MobclickAgent.onEvent(this, eventid,"搜索-搜索_历史");
        }
        hideKeyBoard(etContent);
        Search search = searches.get(position);
        switch (search.getType()) {
            case Search.CONTENT_KEYWORDS:
                goKeyWdAct(search.getContent());
                finish();
                break;
            case Search.CONTENT_URL:
                DEMO_URL = search.getContent();
                if (!DEMO_URL.startsWith("http")) DEMO_URL = "http://" + DEMO_URL;
                selectNetOrDownload();
                break;
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }


//    @Override
//    public void showSearchNavList() {
//
//    }



}
